import * as THREE from 'three';
import HotNewsData from "./HotNewsData.js"
const loader = new THREE.FileLoader();
import {lon2xyz} from "./math.js"
loader.setResponseType('json');
const lineGroup = new THREE.Group();
const model = new THREE.Group();
const lightPillarGroup = new THREE.Group();
const lightWaveGroup = new THREE.Group();
const baseGroup = new THREE.Group();
var n = 3
//加载一个文本文件，并把结果输出到控制台上
loader.load('/world.json',function ( data ) {
  data.features.forEach((area) => {
  // coordinates数据分为单组和多组，将单组的封装为多组
    if(area.geometry.type === 'Polygon'){
        area.geometry.coordinates = [area.geometry.coordinates]
    }
    moreLine(area.geometry.coordinates)
  });
  lineGroup.add(oneLine(allPointArr)) 
})

// 地球体
var R = 110
const geometry = new THREE.SphereGeometry( R, 32, 16 );
const texture = new THREE.TextureLoader().load( '/earth.png');
const material = new THREE.MeshBasicMaterial( { map:texture });
const sphere = new THREE.Mesh( geometry, material );
const materialLine = new THREE.LineBasicMaterial({
  color: 0x00aaaa
});
// 所有边界线顶点坐标合并在一起(每个点都是复制一个)，适合使用LineSegments渲染
var allPointArr = [];
// 批量产生线框
const moreLine = (coordinates)=>{
  coordinates.forEach(polygon=>{
    // 某一个国家的某一个轮廓线的点数组
    var pointArr = []
    polygon[0].forEach(item=>{
      var point = lon2xyz(R,item[0],item[1]);
      // 经纬度不需要太高的精度
      pointArr.push(new THREE.Vector3(Number(point.x).toFixed(n),Number(point.y).toFixed(n),Number(point.z).toFixed(n)));
    })
    // 添加到总轮廓点数组中
    allPointArr.push(pointArr[0])//添加第一个
    pointArr.forEach((item,index)=>{//后面的每一个点都复制一个添加进去
      // 第一个点不复制
      if(index != 0){
        allPointArr.push(item,item)
      }
    })
    // 将第一个点添加最后一个
    allPointArr.push(pointArr[0])
  })
  // 将总的轮廓点数组传入LineSegments方法中,生成一个轮廓线
  // var LineSegments =  oneLine(allPointArr)
  // return LineSegments;
}
// 产生单个线框
var oneLine = (allPointArr)=>{
  const geometry = new THREE.BufferGeometry().setFromPoints( allPointArr );
  const line = new THREE.LineSegments( geometry, materialLine );
  line.position.x += 0.1;
  line.position.y += 0.1;
  line.position.z += 0.1;
  return line;
}
// 产生光圈精灵图
var sprint2 = ()=>{
  // 加载纹理贴图
  var textureSprint = new THREE.TextureLoader().load( '/地球光圈.png');
  // 产生精灵图
  var spriteMaterial = new THREE.SpriteMaterial({
    map: textureSprint,
    transparent: true,//开启透明
    color: 0xffffff,
  });
  var sprite = new THREE.Sprite( spriteMaterial );
  sprite.scale.set(300, 300, 1)
  return sprite
}
const color1 = new THREE.Color(0xff6666)//最大颜色
const color2 = new THREE.Color(0x00ffff)//最小颜色
// 产生光柱效果
const lightPillarFun = (lon,lat,heat)=>{
  const height = heat * R*0.3 + 5
  const geometry = new THREE.PlaneGeometry(R*0.05, height)
  const lightPillarMaterial = new THREE.MeshBasicMaterial({
    color:color2.clone().lerp(color1,heat),
    transparent: true,
    side: THREE.DoubleSide,
    depthWrite: false,//是否对深度缓冲区有任何的影响
    map: new THREE.TextureLoader().load( '/光柱.png'),
  });
  const mesh = new THREE.Mesh(geometry,lightPillarMaterial)
  geometry.rotateX(Math.PI / 2);//光柱高度方向旋转到z轴上
  geometry.translate(0, 0, height / 2);//平移使光柱底部与XOY平面重合
  const group = new THREE.Group();
  group.add(mesh,mesh.clone().rotateZ(Math.PI/2),mesh.clone().rotateZ(Math.PI))
  group.position.copy(lon2xyz(R,lon,lat))
  const lightPillarPoint = group.position.clone().normalize()
  const meshNormal = new THREE.Vector3(0,0,1)
  group.quaternion.setFromUnitVectors(meshNormal,lightPillarPoint)
  return group
}
const geometryLightWave = new THREE.PlaneGeometry(R*0.15,R*0.15)
const lightWave = (lon,lat,heat)=>{
  // 每一个材质都是独立的，不能共用，后面要修改材质的透明度，公用一个会导致同时修改
  const lightWaveMaterial = new THREE.MeshBasicMaterial({
    color:color2.clone().lerp(color1,heat),
    transparent: true,
    depthWrite: false,//是否对深度缓冲区有任何的影响
    map: new THREE.TextureLoader().load( '/标注光圈.png'),
  });
  const mesh = new THREE.Mesh(geometryLightWave,lightWaveMaterial)
  mesh.position.copy(lon2xyz(R*1.01,lon,lat))
  const lightWavePoint = mesh.position.clone().normalize()
  const meshNormal = new THREE.Vector3(0,0,1)
  mesh.quaternion.setFromUnitVectors(meshNormal,lightWavePoint)
  // 每一个光圈的缩放初始值在1-2
  mesh._s = Number((Math.random()+1).toFixed(4)) 
  // mesh.scale.set(mesh._s,mesh._s,1)
  return mesh
}
// 产生底座
const baseGeometry = new THREE.PlaneGeometry(R*0.07,R*0.07)
const base = (lon,lat,heat)=>{
  const baseMaterial = new THREE.MeshBasicMaterial({
    color:color2.clone().lerp(color1,heat),
    transparent: true,
    depthWrite: false,//是否对深度缓冲区有任何的影响
    map: new THREE.TextureLoader().load( '/标注.png'),
  });
  const mesh = new THREE.Mesh(baseGeometry,baseMaterial)
  mesh.position.copy(lon2xyz(R*1.001,lon,lat))
  const lightWavePoint = mesh.position.clone().normalize()
  const meshNormal = new THREE.Vector3(0,0,1)
  mesh.quaternion.setFromUnitVectors(meshNormal,lightWavePoint)
  return mesh
}
// 加载热点新闻数据
HotNewsData.forEach((item,index)=>{
  // 新闻热度，越靠前越高
  const heat = (HotNewsData.length-1 - index)/(HotNewsData.length-1)
  lightPillarGroup.add(lightPillarFun(item.E,item.N,heat))
  lightWaveGroup.add(lightWave(item.E,item.N,heat))
  baseGroup.add(base(item.E,item.N,heat))
})
const render = ()=>{
  if(lightWaveGroup.children.length>0){
    lightWaveGroup.children.forEach(mesh=>{
      if(mesh.type == "Mesh"){
        mesh._s += 0.007;
        if (mesh._s <= 1.5) {
          mesh.material.opacity = (mesh._s-1) * 2;//2等于1/(1.5-1.0)，保证透明度在0~1之间变化
        } else if (mesh._s > 1.5 && mesh._s <= 2) {
          mesh.material.opacity =  1 - (mesh._s - 1.5)*2;//2等于1/(2.0-1.5) mesh缩放2倍对应0 缩放1.5被对应1
        } else {
          mesh._s = 1.0;
        }
        mesh.scale.set(mesh._s,mesh._s,mesh._s)
      }
    })
  }
 
  requestAnimationFrame(render)
}
render()
model.add(sphere,lineGroup,sprint2(),lightPillarGroup,lightWaveGroup,baseGroup);
export {model,sphere};